import { BaseApiService } from './base-api.service'
import { httpClient } from '@/utils/http-client'

/**
 * 用户基础信息接口
 */
export interface UserDto {
  id: string
  userName: string
  email: string
  name?: string
  surname?: string
  phoneNumber?: string
  isActive: boolean
  lockoutEnabled: boolean
  lockoutEnd?: string
  twoFactorEnabled: boolean
  emailConfirmed: boolean
  phoneNumberConfirmed: boolean
  creationTime: string
  lastModificationTime?: string
  lastLoginTime?: string
  roles: string[]
  organizationUnits: Array<{
    id: string
    displayName: string
    role?: string
  }>
  extraProperties?: Record<string, any>
}

/**
 * 创建用户DTO
 */
export interface CreateUserDto {
  userName: string
  name?: string
  surname?: string
  email: string
  phoneNumber?: string
  password: string
  roleNames?: string[]
  organizationUnitIds?: string[]
  isActive?: boolean
  lockoutEnabled?: boolean
  sendConfirmationEmail?: boolean
  sendPasswordResetEmail?: boolean
}

/**
 * 更新用户DTO
 */
export interface UpdateUserDto {
  name?: string
  surname?: string
  email?: string
  phoneNumber?: string
  isActive?: boolean
  lockoutEnabled?: boolean
  roleNames?: string[]
  organizationUnitIds?: string[]
}

/**
 * 用户搜索参数
 */
export interface UserSearchInput {
  filter?: string
  sorting?: string
  isActive?: boolean
  isLockedOut?: boolean
  roleId?: string
  organizationUnitId?: string
  creationTimeMin?: string
  creationTimeMax?: string
  lastLoginTimeMin?: string
  lastLoginTimeMax?: string
}

/**
 * 用户统计信息
 */
export interface UserStatisticsDto {
  totalUsers: number
  activeUsers: number
  inactiveUsers: number
  lockedOutUsers: number
  twoFactorEnabledUsers: number
  usersCreatedThisMonth: number
  usersLoggedInThisMonth: number
  usersByRole: Record<string, number>
  usersByOrganization: Record<string, number>
}

/**
 * 用户批量操作结果
 */
export interface BulkUserOperationResultDto {
  totalCount: number
  successCount: number
  failureCount: number
  results: Array<{
    userId: string
    userName: string
    success: boolean
    error?: string
  }>
}

/**
 * 密码策略DTO
 */
export interface PasswordPolicyDto {
  minLength: number
  requireDigit: boolean
  requireLowercase: boolean
  requireUppercase: boolean
  requireNonAlphanumeric: boolean
  requiredUniqueChars: number
  lockoutDuration: number
  maxFailedAccessAttempts: number
  defaultLockoutTime: number
}

/**
 * 用户登录历史
 */
export interface UserLoginHistoryDto {
  userId: string
  loginTime: string
  logoutTime?: string
  ipAddress: string
  userAgent: string
  isSuccess: boolean
  failureReason?: string
}

/**
 * 用户API服务
 */
export class UserApiService extends BaseApiService {
  constructor() {
    super(httpClient)
  }

  /**
   * 获取用户列表
   */
  async getUsers(params: UserSearchInput = {}, pagination: {
    skipCount?: number
    maxResultCount?: number
  } = {}): Promise<{
    items: UserDto[]
    totalCount: number
  }> {
    return this.getPaged<UserDto>('/api/app/users', { ...params, ...pagination })
  }

  /**
   * 根据ID获取用户详情
   */
  async getUser(id: string): Promise<UserDto> {
    return this.getById<UserDto>('/api/app/users', id)
  }

  /**
   * 创建用户
   */
  async createUser(user: CreateUserDto): Promise<UserDto> {
    return this.create<UserDto>('/api/app/users', user, {
      showSuccessMessage: true,
      successMessage: '用户创建成功'
    })
  }

  /**
   * 更新用户
   */
  async updateUser(id: string, user: UpdateUserDto): Promise<UserDto> {
    return this.update<UserDto>('/api/app/users', id, user, {
      showSuccessMessage: true,
      successMessage: '用户更新成功'
    })
  }

  /**
   * 删除用户
   */
  async deleteUser(id: string): Promise<void> {
    return this.delete('/api/app/users', id, {
      showSuccessMessage: true,
      successMessage: '用户删除成功'
    })
  }

  /**
   * 激活/停用用户
   */
  async changeUserStatus(id: string, isActive: boolean): Promise<void> {
    const action = isActive ? 'activate' : 'deactivate'
    return this.handleRequest(
      () => this.http.patch(`/api/app/users/${id}/change-status`, { isActive }),
      {
        showSuccessMessage: true,
        successMessage: isActive ? '用户已激活' : '用户已停用'
      }
    )
  }

  /**
   * 锁定/解锁用户
   */
  async changeUserLockout(id: string, lockoutEnabled: boolean): Promise<void> {
    return this.handleRequest(
      () => this.http.patch(`/api/app/users/${id}/change-lockout`, { lockoutEnabled }),
      {
        showSuccessMessage: true,
        successMessage: lockoutEnabled ? '用户已锁定' : '用户已解锁'
      }
    )
  }

  /**
   * 重置用户密码
   */
  async resetUserPassword(id: string, newPassword: string): Promise<void> {
    return this.handleRequest(
      () => this.http.post(`/api/app/users/${id}/reset-password`, { newPassword }),
      {
        showSuccessMessage: true,
        successMessage: '密码重置成功'
      }
    )
  }

  /**
   * 为用户分配角色
   */
  async assignRolesToUser(id: string, roleNames: string[]): Promise<void> {
    return this.handleRequest(
      () => this.http.post(`/api/app/users/${id}/assign-roles`, { roleNames }),
      {
        showSuccessMessage: true,
        successMessage: '角色分配成功'
      }
    )
  }

  /**
   * 从用户移除角色
   */
  async removeRolesFromUser(id: string, roleNames: string[]): Promise<void> {
    return this.handleRequest(
      () => this.http.post(`/api/app/users/${id}/remove-roles`, { roleNames }),
      {
        showSuccessMessage: true,
        successMessage: '角色移除成功'
      }
    )
  }

  /**
   * 为用户分配组织
   */
  async assignUserToOrganizations(id: string, organizationIds: string[]): Promise<void> {
    return this.handleRequest(
      () => this.http.post(`/api/app/users/${id}/assign-organizations`, { organizationIds }),
      {
        showSuccessMessage: true,
        successMessage: '组织分配成功'
      }
    )
  }

  /**
   * 从用户移除组织
   */
  async removeUserFromOrganizations(id: string, organizationIds: string[]): Promise<void> {
    return this.handleRequest(
      () => this.http.post(`/api/app/users/${id}/remove-organizations`, { organizationIds }),
      {
        showSuccessMessage: true,
        successMessage: '组织移除成功'
      }
    )
  }

  /**
   * 批量操作用户
   */
  async bulkOperation(params: {
    userIds: string[]
    operation: 'activate' | 'deactivate' | 'lock' | 'unlock' | 'delete'
    parameters?: Record<string, any>
  }): Promise<BulkUserOperationResultDto> {
    return this.handleRequest(
      () => this.http.post<BulkUserOperationResultDto>('/api/app/users/bulk-operation', params),
      {
        showLoading: true,
        loadingMessage: '批量处理用户中...',
        showSuccessMessage: true,
        successMessage: '批量操作完成'
      }
    )
  }

  /**
   * 批量删除用户
   */
  async bulkDeleteUsers(userIds: string[]): Promise<BulkUserOperationResultDto> {
    return this.batchDelete('/api/app/users', userIds, {
      showLoading: true,
      loadingMessage: '批量删除用户中...',
      showSuccessMessage: true,
      successMessage: '批量删除完成'
    })
  }

  /**
   * 导入用户
   */
  async importUsers(file: File, options: {
    sendWelcomeEmail?: boolean
    generateRandomPassword?: boolean
    overwriteExisting?: boolean
  } = {}): Promise<BulkUserOperationResultDto> {
    return this.import(
      '/api/app/users/import',
      {
        file,
        ...options
      },
      {
        showLoading: true,
        loadingMessage: '导入用户中...',
        showSuccessMessage: true,
        successMessage: '用户导入完成'
      }
    )
  }

  /**
   * 导出用户
   */
  async exportUsers(params: UserSearchInput = {}, format: 'json' | 'excel' | 'csv' = 'xlsx'): Promise<void> {
    return this.export('/api/app/users/export', {
      ...params,
      format
    }, {
      showLoading: true,
      loadingMessage: '导出用户中...',
      filename: `users_export_${Date.now()}.${format}`
    })
  }

  /**
   * 获取用户导入模板
   */
  async downloadUserTemplate(format: string = 'xlsx'): Promise<void> {
    return this.getImportTemplate('/api/app/users', format, {
      filename: `users_template.${format}`
    })
  }

  /**
   * 验证用户导入数据
   */
  async validateUserImport(file: File): Promise<{
    isValid: boolean
    errors: Array<{
      line: number
      field: string
      message: string
    }>
    warnings: Array<{
      line: number
      message: string
    }>
  }> {
    return this.handleRequest(
      () => this.http.upload('/api/app/users/validate-import', file),
      {
        showLoading: true,
        loadingMessage: '验证导入数据中...'
      }
    )
  }

  /**
   * 获取用户统计信息
   */
  async getUserStatistics(params: {
    startDate?: string
    endDate?: string
    groupBy?: 'day' | 'week' | 'month'
  } = {}): Promise<UserStatisticsDto> {
    return this.getStatistics<UserStatisticsDto>('/api/app/users/statistics', params)
  }

  /**
   * 获取用户登录历史
   */
  async getUserLoginHistory(userId: string, params: {
    startDate?: string
    endDate?: string
    skipCount?: number
    maxResultCount?: number
  } = {}): Promise<{
    items: UserLoginHistoryDto[]
    totalCount: number
  }> {
    return this.getPaged<UserLoginHistoryDto>(`/api/app/users/${userId}/login-history`, params)
  }

  /**
   * 获取密码策略
   */
  async getPasswordPolicy(): Promise<PasswordPolicyDto> {
    return this.handleRequest(
      () => this.http.get<PasswordPolicyDto>('/api/app/users/password-policy'),
      { showLoading: false }
    )
  }

  /**
   * 搜索用户建议
   */
  async searchUserSuggestions(keyword: string, limit: number = 10): Promise<Array<{
    id: string
    userName: string
    email: string
    name?: string
    surname?: string
  }>> {
    return this.searchSuggestions<Array<{
      id: string
      userName: string
      email: string
      name?: string
      surname?: string
    }>>('/api/app/users/suggestions', keyword, { limit })
  }

  /**
   * 验证用户数据
   */
  async validateUser(user: CreateUserDto | UpdateUserDto, isUpdate = false): Promise<{
    isValid: boolean
    errors: Array<{
      field: string
      message: string
    }>
  }> {
    const url = isUpdate ? '/api/app/users/validate-update' : '/api/app/users/validate-create'
    return this.validate(user, { showLoading: false })
  }

  /**
   * 检查用户名是否可用
   */
  async checkUsernameAvailability(username: string, excludeUserId?: string): Promise<{
    isAvailable: boolean
    message?: string
  }> {
    const params: any = { username }
    if (excludeUserId) {
      params.excludeUserId = excludeUserId
    }

    return this.handleRequest(
      () => this.http.get('/api/app/users/check-username-availability', params),
      { showLoading: false }
    )
  }

  /**
   * 检查邮箱是否可用
   */
  async checkEmailAvailability(email: string, excludeUserId?: string): Promise<{
    isAvailable: boolean
    message?: string
  }> {
    const params: any = { email }
    if (excludeUserId) {
      params.excludeUserId = excludeUserId
    }

    return this.handleRequest(
      () => this.http.get('/api/app/users/check-email-availability', params),
      { showLoading: false }
    )
  }

  /**
   * 获取用户权限摘要
   */
  async getUserPermissionSummary(userId: string): Promise<{
    userId: string
    userName: string
    permissions: Array<{
      name: string
      displayName: string
      source: string
    }>
    roles: Array<{
      name: string
      displayName: string
    }>
    organizations: Array<{
      id: string
      name: string
      role: string
    }>
    totalPermissions: number
  }> {
    return this.handleRequest(
      () => this.http.get(`/api/app/users/${userId}/permission-summary`),
      { showLoading: false }
    )
  }

  /**
   * 复制用户权限
   */
  async copyUserPermissions(sourceUserId: string, targetUserIds: string[]): Promise<{
    successCount: number
    failureCount: number
    results: Array<{
      userId: string
      success: boolean
      error?: string
    }>
  }> {
    return this.handleRequest(
      () => this.http.post('/api/app/users/copy-permissions', {
        sourceUserId,
        targetUserIds
      }),
      {
        showLoading: true,
        loadingMessage: '复制权限中...',
        showSuccessMessage: true,
        successMessage: '权限复制完成'
      }
    )
  }

  /**
   * 同步用户到Keycloak
   */
  async syncUserToKeycloak(userId: string): Promise<{
    success: boolean
    message: string
    keycloakUserId?: string
  }> {
    return this.handleRequest(
      () => this.http.post(`/api/app/users/${userId}/sync-keycloak`),
      {
        showLoading: true,
        loadingMessage: '同步用户到Keycloak中...',
        showSuccessMessage: true,
        successMessage: '用户同步成功'
      }
    )
  }

  /**
   * 批量同步用户到Keycloak
   */
  async bulkSyncUsersToKeycloak(userIds: string[]): Promise<{
    successCount: number
    failureCount: number
    results: Array<{
      userId: string
      success: boolean
      message?: string
    }>
  }> {
    return this.handleRequest(
      () => this.http.post('/api/app/users/bulk-sync-keycloak', { userIds }),
      {
        showLoading: true,
        loadingMessage: '批量同步用户到Keycloak中...',
        showSuccessMessage: true,
        successMessage: '批量同步完成'
      }
    )
  }
}

// 创建单例实例
export const userApi = new UserApiService()